String formatting and Literals are incredibly useful tools for building dynamic strings in python programs. They allow you to build strings using variable input, and change the default behaviour of strings respectively.
Some terms to help you navigate the post
In python there are a set of prefixes (string literals) that create completely different effects. For example placing an r or R in front of a string instantiation will cause it to ignore special characters such as \n or \t.
Example:
my_string = "Hello \n\tWorld"
print(my_string) """Would print:
Hello
World """
my_string = r"Hello \n\tWorld" # Also works with R"Hello \n\tWorld"
print(my_string) # Would print: Hello \n\tWorld
For details on other string prefixes, see the python 3 string literals reference docs.
The process of dynamically building strings based on variables and preset values. For example, lets say you are bulding a client dashboard that displays a welcome message (like the one in the example in string_formatting.py
). For this you might want to create a greeting that is along the lines of:
Hello <name> The weather today is <current_temperature> degrees. You have <email_count> new emails..
To do this you could do:
name = "John Smith" # A dummy name
email_count = 3 # A representation of users # of new emails
current_temperature = 20.3567 # A representation of the current temperature in celsius
greeting = f"Hello, {name} The weather today is {current_temperature} degrees. You have {email_count} new emails."
print(greeting)
Note that the preferred method of string formatting uses String literals. You can see examples of all 4 methods of formatting in string_formatting.py
All of the code in the two demos require no external dependencies, they can be run by using python string_formatting.py
or python string_literals.py
String formatting has obvious real world applications in just about every application, String Literals are somewhat less immediately obvious. Besides for providing the latest format syntax (fstrings), they also allow you to do things like raw strings (as seen in the example above) and also byte strings for things like security modules.
"""
Description:
A demo of the different forms of string Literals available. SEE: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
"""
# Raw strings; These are strings that will completely ignore special characters such as \n or \t
my_string = "Hello \n\tWorld"
print(my_string) """Would print:Hello
World"""
my_string = r"Hello \n\tWorld" # Also works with R"Hello \n\tWorld"
print(my_string) # Would print: Hello \n\tWorld
# Byte strings; These take the string provided and build a bytes object.
# SEE: https://www.python.org/dev/peps/pep-3112/ For reference about byte string literals
# SEE: https://docs.python.org/3/library/stdtypes.html#bytes For referenec about byte objects
my_string = "Hello"
print(type(my_string))
my_string = b"Hello"
print(type(my_string))
"""Unicode Literals; Unicode literals are no longer necessary,
but some legacy code may contain them. It creates a unicode object with the string as the argument
SEE: https://docs.python.org/3/c-api/unicode.html"""
my_string = "Hello"
print(type(my_string))
my_string = u"Hello"
print(type(my_string))
"""FStrings; Format strings can be seen in more detail in string_formatting.py.
But the basics are it allows you to construct strings using variables"""
name = "John Doe"
greeting = f"Hello, {name}"
print(greeting)
"""
Description:
A demo of the 4 primary methods of string formatting.
"""
name = "John Smith" # A dummy name
email_count = 3 # A representation of users # of new emails
current_temperature = 20.3567 # A representation of the current temperature in celsius
##### ===== New/Current Style ===== #####
""" fstrings/string interpoloation; This is the most current way of doing things,
it allows you to use embedded variable calls using {variable_name}
SEE: https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals """
greeting = f"Hello, {name} The weather today is {current_temperature} degrees. You have {email_count} new emails."
print(greeting)
"""
format function; Allows you to put placeholders {} to be filled as arguments during the function call
SEE: https://docs.python.org/3.4/library/string.html#format-examples for more examples
"""
greeting = "Hello, {} The weather today is {:03.2f} degrees. You have {} new emails.".format(name, current_temperature, email_count)
print(greeting)
##### ===== Old Style ===== #####
# % formatting;
greeting = "Hello, %s The weather today is %03.2f degrees. You have %d new emails." % (name, current_temperature, email_count)
print(greeting)
# +; you can concatenate strings together using the + operator. NOTE: This uses the string classes' __add__ method.
greeting = "Hello, " + name + " The weather today is " + str(current_temperature) + " degrees. You have " + str(email_count) + " new emails."
print(greeting)